package cc.admin.modules.graduate.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.aspect.annotation.AutoLog;
import cc.admin.common.sys.base.controller.BaseController;
import cc.admin.common.sys.query.QueryGenerator;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.modules.graduate.entity.Topic;
import cc.admin.modules.graduate.entity.UserForumLike;
import cc.admin.modules.graduate.service.IUserForumLikeService;
import cc.admin.modules.sys.entity.SysCascade;
import cc.admin.modules.sys.service.ISysCascadeService;
import cc.admin.modules.graduate.entity.Forum;
import cc.admin.modules.graduate.service.IForumService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 话题树
 * @Author: cc-admin
 * @Date: 2025-02-13
 * @Version: V1.0.0
 */
@Slf4j
@Api(tags = "话题树")
@RestController
@RequestMapping("/forum")
public class ForumController extends BaseController<Forum, IForumService> {
    @Autowired
    private IForumService forumService;

    @Autowired
    private IUserForumLikeService userForumLikeService;
    /**
     * 分页列表查询
     *
     * @param key
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "话题树-分页列表查询")
    @ApiOperation(value = "话题树-分页列表查询", notes = "话题树-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            @RequestParam(name = "key", required = false) String key,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<Forum> queryWrapper = QueryGenerator.initQueryWrapper(new Forum(), req.getParameterMap());
        if (StrUtil.isNotEmpty(key)) {

        }
        queryWrapper.isNull("parent_id");
        List<String> collect = Arrays.stream(key.split(",")).collect(Collectors.toList());
        queryWrapper.in(collect.size()>=1,"topic_value", collect);
        Page<Forum> page = new Page<Forum>(pageNo, pageSize);
        IPage<Forum> pageList = forumService.page(page, queryWrapper);
        pageList.getRecords().forEach(forum -> {
            forumContent(forum);
            LambdaQueryWrapper<Forum> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Forum::getParentId, forum.getId());
            lambdaQueryWrapper.isNull(Forum::getDiscussion);
            List<Forum> childlist = forumService.list(lambdaQueryWrapper);
            childlist.forEach(childForum -> {
                forumContent(childForum);
                LambdaQueryWrapper<Forum> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(Forum::getParentId, childForum.getId());
                lambdaQueryWrapper2.isNotNull(Forum::getDiscussion);
                List<Forum> childlist2 = forumService.list(lambdaQueryWrapper2);
                childlist2.forEach(childForum2->{
                    forumContent(childForum2);
                    LambdaQueryWrapper<Forum> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper3.eq(Forum::getParentId, childForum2.getId());
                    lambdaQueryWrapper3.isNotNull(Forum::getDiscussion);
                    List<Forum> childlist3 = forumService.list(lambdaQueryWrapper3);
                    childForum2.setChildForums(childlist3);
                });
                childForum.setChildForums(childlist2);
            });
            forum.setChildForums(childlist);
        });
        return Result.ok(pageList);
    }

    public void forumContent(Forum forum) {
        String topicLabel = forum.getTopicLabel();
        String topicValue = forum.getTopicValue();
        Topic topic = new Topic(topicLabel, topicValue);
        forum.setTopic(topic);
        if (forum.getViedoUrlText() != null && forum.getViedoUrlText().split(",") != null) {
            List<String> videoUrls = Arrays.stream(forum.getViedoUrlText().split(",")).collect(Collectors.toList());
            forum.setViedoUrls(videoUrls);
        }
    }

    @AutoLog(value = "获取用户喜欢的formId")
    @ApiOperation(value = "获取用户喜欢的formId", notes = "获取用户喜欢的formId")
    @GetMapping(value = "/getUserLike")
    public Result<?> getUserLike(){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        LambdaQueryWrapper<UserForumLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserForumLike::getUserId,user.getUsername());
        List<UserForumLike> list = userForumLikeService.list(queryWrapper);
        List<String> forumIdList = list.stream().map(UserForumLike::getForumId).collect(Collectors.toList());

        return Result.ok(forumIdList);
    }

    /**
     * 添加
     *
     * @param forum
     * @return
     */
    @AutoLog(value = "话题树-添加")
    @ApiOperation(value = "话题树-添加", notes = "话题树-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Forum forum) {
        forum.setId(IdUtil.objectId());

        forumService.saveForum(forum);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param forum
     * @return
     */
    @AutoLog(value = "话题树-编辑")
    @ApiOperation(value = "话题树-编辑", notes = "话题树-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Forum forum) {
        forumService.updateById(forum);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "话题树-通过id查询")
    @ApiOperation(value = "话题树-通过id查询", notes = "话题树-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Forum forum = forumService.getById(id);
        forumContent(forum);
        LambdaQueryWrapper<Forum> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Forum::getParentId, forum.getId());
        lambdaQueryWrapper.isNull(Forum::getDiscussion);
        List<Forum> childlist = forumService.list(lambdaQueryWrapper);
        childlist.forEach(childForum -> {
            forumContent(childForum);
            LambdaQueryWrapper<Forum> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Forum::getParentId, childForum.getId());
            lambdaQueryWrapper2.isNotNull(Forum::getDiscussion);
            List<Forum> childlist2 = forumService.list(lambdaQueryWrapper2);
            childlist2.forEach(childForum2->{
                forumContent(childForum2);
                LambdaQueryWrapper<Forum> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper3.eq(Forum::getParentId, childForum2.getId());
                lambdaQueryWrapper3.isNotNull(Forum::getDiscussion);
                List<Forum> childlist3 = forumService.list(lambdaQueryWrapper3);
                childForum2.setChildForums(childlist3);
            });
            childForum.setChildForums(childlist2);
        });
        forum.setChildForums(childlist);
        return Result.ok(forum);
    }

    /**
     * 复制
     *
     * @param id
     * @param name
     * @return
     */
    @AutoLog(value = "话题树-复制")
    @ApiOperation(value = "话题树-复制", notes = "话题树-复制")
    @PostMapping(value = "/copy")
    public Result<?> copy(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "name", required = true) String name) {
        Forum forum = forumService.getById(id);
        forum.setId(IdUtil.fastUUID());
        forum.setCreateTime(new Date());
        forumService.save(forum);
        return Result.ok("复制成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "话题树-通过id删除")
    @ApiOperation(value = "话题树-通过id删除", notes = "话题树-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        forumService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "话题树-批量删除")
    @ApiOperation(value = "话题树-批量删除", notes = "话题树-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.forumService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }



    /**
     * 导出excel
     *
     * @param request
     * @param forum
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Forum forum) {
        return super.exportXls(request, forum, Forum.class, "话题树");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Forum.class);
    }

}
